import React, { useEffect, useRef, useState } from "react";

import styled from "styled-components";

const DropdownContainer = styled.div`
  position: relative;
  display: inline-block;
  width: 100%;
`;

const DropdownButton = styled.button`
  background-color: #4caf50;
  color: ${(props) => (props.selected ? "white" : "green")};
  padding: 16px;
  font-size: 16px;
  border: none;
  width: 100%;
`;

const DropdownContent = styled.div`
  display: ${(props) => (props.open ? "block" : "none")};
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;

  & a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
  }

  & a:hover {
    background-color: #ddd;
  }
`;

const Dropdown = ({ placeHolder, data, onSelect }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [activeItem, setActiveItem] = useState({});
  const dropdownRef = useRef(null);

  const handleClick = (index) => {
    setActiveItem(data[index]);
    onSelect && onSelect({ index, ...data[index] });
    setTimeout(() => {
      setIsOpen(false); // for animation
    }, 100);
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <DropdownContainer ref={dropdownRef}>
      <DropdownButton
        selected={!!activeItem.title}
        onClick={() => setIsOpen(!isOpen)}
      >
        {activeItem.title || placeHolder}
      </DropdownButton>
      <DropdownContent open={isOpen}>
        {data.map((item, index) => {
          return (
            <a href="#" key={item.key} onClick={() => handleClick(index)}>
              {item.title}
            </a>
          );
        })}
      </DropdownContent>
    </DropdownContainer>
  );
};

export default Dropdown;
